package main

import (
	"fmt"
	"io"
	"linx/lnet"
	"net"
)

// 模拟客户端
func main() {
	// 1。 创建一个连接
	fmt.Println("客户端启动！")
	dial, err := net.Dial("tcp", "127.0.0.1:7777")
	if err != nil {
		fmt.Printf("dial err:%s\n", err.Error())
		return
	}
	var cnt uint32
	cnt = 1
	for {
		dp := lnet.NewDataPack()
		binaryMsg, err := dp.Pack(lnet.NewMsgPackage(cnt, []byte("sdfsfs")))
		if err != nil {
			fmt.Println("Pack err:", err.Error())
			return
		}
		if _, err := dial.Write(binaryMsg); err != nil {
			fmt.Println("Write err:", err.Error())
			return
		}
		// 读取 head 二进制
		binaryHead := make([]byte, dp.GetHeadLen())
		if _, err := io.ReadFull(dial, binaryHead); err != nil {
			fmt.Println("Read head err:", err.Error())
			return
		}

		// 读取 head
		msgHead, err := dp.Unpack(binaryHead)
		if err != nil {
			fmt.Println("Unpack head err:", err.Error())
			return
		}

		// 读取 data
		if msgHead.GetMsgLen() > 0 {
			msg := msgHead.(*lnet.Message)
			msg.Data = make([]byte, msg.GetMsgLen())
			if _, err := io.ReadFull(dial, msg.Data); err != nil {
				fmt.Println("Read data err:", err.Error())
				return
			}
			fmt.Printf("Client resp:%+v | data:%s\n", msg, string(msg.Data))
		}
		cnt++
		if cnt == 3 {
			break
		}
	}
	select {}

}
